// 医保挂号
import { commonPost } from '@api/data'
import { route, appointent, recipel } from "@js/mixins"
import { CallMedIns } from '@api/tools/MedInsTrade.js'
import { Printerconf} from '@api/tools/rprinter.js'
export const MedInsRegistTrade = {
    mixins: [route, appointent, recipel],
    data() {
        return {
            YB: new CallMedIns(),
            pconf:new Printerconf(),
            ybregistmsg: {},
            upfeemsg: {},
            preconfirmmsg: {},
            confirmmsg: {},
            payinfo:{
                barCode:"",
                status: "",
                amount:"",
                outPayTradno:"",
                rcptNo:"",
                transNo:"",
                payWay:"",
              },
        }
    },
    methods: {
            async CMIRegist() {
            let appointmentInfo = this.$store.state.appointment.appointmentInfo;
            var miinfo=this.$store.state.user.miinfo;
            console.log("医保个人编号="+miinfo[0]);
            let data = {}
            //step 1 获取医保挂号登记报文
            data.url = "/api/CMIRegist"
            data.payload = {
                hisOperNo: this.$store.state.terminfo.yboperno,
                scheduleId: appointmentInfo.scheduleId,
                miPersonId:miinfo[0],
                tradeType: '0',//交易类型（0上传，1反交易）
                medInsType: '0',//省市医保标志（0市医保，1省医保）
                medInsBusinessInfo: this.$store.state.terminfo.medInsBusinessInfo,
            }
             commonPost(data).then(res => {
                this.ybregistmsg = res.data;
                this.$store.dispatch('medicalInsurance/updateregmsghis', res.data)
                this.CMIRegistdll();
            });
        },
        async CMIRegistdll() {
            //step 1.1 医保dll挂号登记
            console.log("medInsRegistMsg=" + this.ybregistmsg.medInsRegistMsg);
            try {
                var ybghdjinfo = await this.YB.Trade(1, this.ybregistmsg.medInsRegistMsg);
                //这里的ybghdjinfo放到store中
                this.$store.dispatch('medicalInsurance/updateregmsgdll', ybghdjinfo)
                console.log("挂号登记dll返回：" + this.$store.state.medicalInsurance.regmsgdll);
                this.$store.dispatch('user/updatemisYbPay', true);//医保支付
                let orginfo = this.$store.state.terminfo.orginfo;
                if(orginfo.cmiid==='104'){//延吉挂号登记后即医保扣款结束
                      //step 2 
                      var temp2 = ybghdjinfo.split("^")[2];
                      var userpay = temp2.split("|")[3];//个人现金支付
                      console.log("userpay:"+userpay);
                      var ybPay = temp2.split("|")[1]; // 本次医保账户支付金额
                      console.log("ybPay:"+ybPay);
                        if (userpay.indexOf('.') == 0) {
                            userpay = '0' + userpay;
                        }
                        this.$store.dispatch('user/updateuserpay', userpay);
                        this.$store.dispatch('user/updateybpay', ybPay);
                        if (parseFloat(userpay) > 0) {
                            this.$store.dispatch('route/updatePreStageEnd', "mzgh")
                            this.$router.push({ name: "payments", query: { from: "mzgh" } });
                        }
                        else {
                            this.payinfo.amount='0';
                            this.payinfo.payWay='医保';
                            this.$store.dispatch("payrecord/updatepayinfo", this.payinfo);
                             await  this.sendRegConfirm();
                        }
                }
                else{//需要走费用上传的九台，吉大一
                    //step 2 费用上传
                    await this.CMIUpFee(this.ybregistmsg.regReciptId);
                }
 
            }
            catch (e) {
                this.$router.push({ name: "home" });
                this.YB.Trade(1, this.ybregistmsg.medInsRetRegistMsg);
                this.$notify({
                    title: '抱歉',
                    offset: 400,
                    message: '医保挂号登记失败：' + e.message,
                    type: 'warning'
                });
            }
        },
        //step 2  市医保费用上传
        async CMIUpFee(temp) {
            let appointmentInfo = this.$store.state.appointment.appointmentInfo;
            let data = {}
            data.url = "/api/CMIUpFeeDetails"
            data.payload = {
                hisOperNo: this.$store.state.terminfo.yboperno,
                scheduleId: appointmentInfo.scheduleId,
                tradeType: '0',//交易类型（0上传，1反交易）
                regReciptId: temp,
                businessType: '1',
                patientId: this.$store.state.user.userinfo.patientId,
                medInsType: '0',//省市医保标志（0市医保，1省医保）
                drugOrTreat: '1',//药品诊疗标志（0是药品1是诊疗）
                medInsBusinessInfo: this.$store.state.terminfo.medInsBusinessInfo,
            }
            commonPost(data).then(res => {
                this.upfeemsg = res.data;
                this.$store.dispatch('medicalInsurance/updateupfeehis', res.data)
                this.CMIUpFeedll();
            }).catch(e=>{
                LogError("获取his费用上传报文失败，医保挂号登记撤销报文："+this.ybregistmsg.medInsRetRegistMsg);
                this.YB.Trade(1, this.ybregistmsg.medInsRetRegistMsg);
              });
           
        },
        async CMIUpFeedll() {
            //step 2.1 医保dll费用上传
            try {
                var upfeeinfo = await this.YB.Trade(1, this.upfeemsg.medInsUpFeeMsg);
                   //step 3 费用预结算
                  await this.CMIRegPreConfirm();
                //这里的upfeeinfo数据怎么放？
            } catch (e) {
                LogError("医保费用上传失败，医保挂号登记撤销："+this.ybregistmsg.medInsRetRegistMsg);
                await this.YB.Trade(1, this.ybregistmsg.medInsRetRegistMsg);
                this.$router.push({ name: "home" });
                this.$notify({
                    title: '抱歉',
                    offset: 400,
                    message: '医保交易失败：' + e.message,
                    type: 'warning'
                });
            }
            //这里的ybghdjinfo放到store中
            // this.$store.dispatch('medicalInsurance/updateregmsgdll',ybghdjinfo)
         
        },
        //step 3  市医保预结算
        async CMIRegPreConfirm() {
            let appointmentInfo = this.$store.state.appointment.appointmentInfo;
            let data = {}
            data.url = "/api/CMIBillConfirm"
            data.payload = {
                hisOperNo: this.$store.state.terminfo.yboperno,
                scheduleId: appointmentInfo.scheduleId,
                tradeType: '2',//交易类型（0上传，1反交易,2预结算）
                regReciptId: this.ybregistmsg.regReciptId,
                patientId: this.$store.state.user.userinfo.patientId,
                businessType: '1',
                medInsType: '0',//省市医保标志（0市医保，1省医保）
                medInsBusinessInfo: this.$store.state.terminfo.medInsBusinessInfo,
            }
            commonPost(data).then(res => {
                this.preconfirmmsg = res.data;
                this.CMIRegPreConfirmdll();
            }).catch(e=>{
                LogError("获取his预结算报文失败，医保费用撤销"+this.upfeemsg.medInsRetUpFeeMsg);
                this.YB.Trade(1, this.upfeemsg.medInsRetUpFeeMsg);
                this.YB.Trade(1, this.ybregistmsg.medInsRetRegistMsg);

              });
          
        },
        async CMIRegPreConfirmdll() {
            //step 3.1 医保dll预结算上传
            try {
                var preconfirminfo = await this.YB.Trade(1, this.preconfirmmsg.medInsBillConfirmMsg);
                this.$store.dispatch('user/updatemisYbPay', true);//医保支付
                //这里的preconfirminfo数据怎么放？
                var temp2 = preconfirminfo.split("^")[2];
                var userpay = temp2.split("|")[24];//个人现金支付
                console.log("userpay:"+userpay);
                var ybPay = temp2.split("|")[23]; // 本次医保账户支付金额
                console.log("ybPay:"+ybPay);
                if (userpay.indexOf('.') == 0) {
                    userpay = '0' + userpay;
                }
                this.$store.dispatch('user/updateuserpay', userpay);
                if (parseFloat(userpay) > 0) {                  
                    this.$store.dispatch('route/updatePreStageEnd', "mzgh")
                    this.$router.push({ name: "payments", query: { from: "mzgh" } });
                }
                else {
                    this.payinfo.amount='0';
                    this.payinfo.payWay='医保';
                    this.$store.dispatch("payrecord/updatepayinfo", this.payinfo);
                    await this.CMIRegConfirm();
                }
            } catch (e) {
                LogError("医保预结算失败，医保费用撤销："+this.upfeemsg.medInsRetUpFeeMsg);
                await this.YB.Trade(1, this.upfeemsg.medInsRetUpFeeMsg);
                await this.YB.Trade(1, this.ybregistmsg.medInsRetRegistMsg);
                this.$router.push({ name: "home" });
                this.$notify({
                    title: '抱歉',
                    offset: 400,
                    message: '医保预结算失败，医保费用已撤销：' + e.message,
                    type: 'warning'
                });
            }
        },
        //市医保结算
        async CMIRegConfirm() {
            let appointmentInfo = this.$store.state.appointment.appointmentInfo;
            let data = {}
            data.url = "/api/CMIBillConfirm"
            data.payload = {
                hisOperNo: this.$store.state.terminfo.yboperno,
                scheduleId: appointmentInfo.scheduleId,
                tradeType: '0',//交易类型（0上传，1反交易,2预结算）
                regReciptId: this.$store.state.medicalInsurance.regmsghis.regReciptId,
                patientId: this.$store.state.user.userinfo.patientId,
                businessType: '1',
                medInsType: '0',//省市医保标志（0市医保，1省医保）
                medInsBusinessInfo: this.$store.state.terminfo.medInsBusinessInfo,
            }
            commonPost(data).then(res => {
                this.confirmmsg = res.data;
                this.$store.dispatch('medicalInsurance/updateconfirmhis', res.data);
                this.CMIRegConfirmdll();
            }).catch(e=>{
                LogError("获取结算报文失败，预结算撤销"+this.preconfirmmsg.medInsRetBillConfirmMsg);
                this.YB.Trade(1, this.upfeemsg.medInsRetUpFeeMsg);
                this.YB.Trade(1, this.ybregistmsg.medInsRetRegistMsg);
                this.YB.Trade(1,  this.preconfirmmsg.medInsRetBillConfirmMsg);
              });
           

        },
        async CMIRegConfirmdll() {
           try {
                //step 4.1 医保dll结算
                var confirminfo = await this.YB.Trade(1, this.confirmmsg.medInsBillConfirmMsg);
                //这里的confirminfo数据怎么放？
                this.$store.dispatch('medicalInsurance/updateconfirmdll', confirminfo)
                this.sendRegConfirm();
            }catch (e) {
                LogError("医保结算失败，结算撤销："+ this.confirmmsg.medInsRetBillConfirmMsg);
                //结算撤销
                await this.YB.Trade(1,  this.$store.state.medicalInsurance.confirmhis.medInsRetBillConfirmMsg);
                //费用撤销
                await this.YB.Trade(1, this.$store.state.medicalInsurance.upfeehis.medInsRetUpFeeMsg);
                //挂号登记撤销
                await  this.YB.Trade(1, this.$store.state.medicalInsurance.regmsghis.medInsRetRegistMsg);
                this.$router.push({ name: "home" });
                this.$notify({
                    title: '抱歉',
                    offset: 400,
                    message: '医保交易失败，结算已撤销：' + e.message,
                    type: 'warning'
                });
            }
         
        
        },
    }
}

function LogError(str) {
    console.log(`%c ${str}`, 'color:red');
}